package com.shu.controller;

import com.shu.dto.FileInfo;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @author shujinhao
 */
@RestController
@RequestMapping("/file")
public class FileController {
    private final static String folder = "F:\\";

    /**
     * 上传文件
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping
    public FileInfo upload(MultipartFile file) throws Exception {
        System.out.println(file.getName());
        System.out.println(file.getOriginalFilename());
        System.out.println(file.getSize());


        File  localFile = new File(folder,System.currentTimeMillis()+".txt");
        //转存文件
        file.transferTo(localFile);

        return new FileInfo(localFile.getAbsolutePath());
    }

    @GetMapping("/{id}")
    public void download(@PathVariable String id , HttpServletRequest request, HttpServletResponse response) throws IOException {
        //java1.7 流可以放在try的括号里面，就可以自动关闭
        try ( InputStream inputStream = new FileInputStream(new File(folder,id+".txt"));
              OutputStream outputStream = response.getOutputStream();
              ){

            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition","attachment;filename=test.txt");
            //输入流，复制到输出流里面
            IOUtils.copy(inputStream,outputStream);
            outputStream.flush();
        }

    }
}
